package com.demo.study.creative.d05_singleton;

/**
 * 双重判断，解决多线程问题
 *
 * @author Baymax
 * @since 2021/1/18
 */
public class ThreadSingleton {
    private static ThreadSingleton instance = null;

    private ThreadSingleton() {
    }

    private static ThreadSingleton instance() {
        if (instance == null) {
            synchronized (ThreadSingleton.class) {
                if (instance == null) {
                    try {
                        Thread.sleep(5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    instance = new ThreadSingleton();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    ThreadSingleton sgt1 = ThreadSingleton.instance();
                    System.out.println("current task: " + sgt1.hashCode());
                }
            }).start();
        }
    }
}
